<template>
  <div>
    <div class="title">发布积分优惠券</div>
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="fromRef"
      class="demo-ruleForm"
    >
      <el-form-item label="有效时间" prop="useDateValue">
        <el-radio
          v-model="timeRadio"
          label="setTime"
          @change="chooseTimeType"
          :disabled="disType"
          >固定时间</el-radio
        >
        <el-radio
          v-model="timeRadio"
          label="immediate"
          @change="chooseTimeType"
          :disabled="disType"
          >领券立即生效</el-radio
        >
        <div style="margin: 10px 0px 10px 80px">
          <span v-if="timeRadio === 'setTime'">
            <el-date-picker
              v-model="ruleForm.useDateValue.startTime"
              type="date"
              placeholder="开始日期"
              :picker-options="pickerOptions"
              style="width: 200px"
              :disabled="disType"
            ></el-date-picker>
            <el-date-picker
              v-model="ruleForm.useDateValue.endTime"
              type="date"
              placeholder="结束日期"
              style="width: 200px; margin-left: 10px"
            ></el-date-picker>
          </span>
          <span v-else
            >领券当日起
            <el-input-number
              :min="0"
              :controls="false"
              style="width: 80px; margin: 10px 0px"
              v-model="ruleForm.useDateValue.effectiveDays"
              :disabled="disType"
            ></el-input-number
            >天内可用
          </span>
        </div>
      </el-form-item>
      <el-form-item label="活动规则" prop="actRules">
        <AddCouponTable ref="addComp" :couponContent="couponContent" />
      </el-form-item>
      <el-form-item label="商品选择" prop="actRules">
        <ApointGoods
          style="padding-left: 80px"
          ref="apointComp"
          :actType="actType"
          :content="couponContent"
        />
      </el-form-item>
    </el-form>
    <div class="pageButtom">
      <el-button @click="$router.push({ name: 'integralMallIndex' })"
        >取消</el-button
      >
      <el-button type="primary" @click="save">保存</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Ref } from "vue-property-decorator";
import AddCouponTable from "./issueCouponForm/AddCouponTable.vue";
import ApointGoods from "../../common/ApointGoods.vue";
import DateUtil from "@/store/modules/date";
import {
  addCoupon,
  couponDetail,
  editCoupon,
} from "@/api/couponActivity/coupon";
Component.registerHooks(["beforeRouteLeave"]);

@Component({
  components: {
    AddCouponTable,
    ApointGoods,
  },
})
export default class IssueCoupon extends Vue {
  @Ref()
  readonly fromRef: HTMLFormElement;

  @Ref()
  readonly addComp: HTMLFormElement;

  @Ref()
  readonly apointComp: HTMLFormElement;

  validatePass(rule, value, callback) {
    const start = new Date(value.startTime).getTime();
    const end = new Date(new DateUtil("").getYMD(new Date())).getTime();
    if (this.timeRadio === "setTime") {
      if (!value.endTime || !value.startTime) {
        callback(new Error("请输入活动时间"));
      } else {
        if (value.startTime.getTime() > value.endTime.getTime()) {
          callback(new Error("结束时间不能小于开始时间"));
        }
        if (start < end) {
          callback(new Error("开始时间不能小于当前时间"));
        }
      }
    } else {
      if (!value.effectiveDays) {
        callback(new Error("请输入活动时间"));
      }
    }
  }

  rulevalidate() {
    console.log("test");
  }

  pickerOptions = {
    disabledDate(time) {
      const now = new Date(new Date().toLocaleDateString()).getTime();
      return time.getTime() < now;
    },
  };

  actType = "AddActivity";

  /** 优惠券使用时间 */
  timeRadio = "setTime";

  /** 禁用状态 */
  disType = false;

  /** nameid 用name 字段控制 */
  nameId = "";

  ruleForm = {
    useDateValue: {
      startTime: "" as any,
      endTime: "" as any,
      effectiveDays: "",
    },
    type: [],
  };

  rules = {
    useDateValue: [
      {
        validator: this.validatePass,
        required: true,
        trigger: "blur",
      },
    ],
    actRules: [
      { validator: this.rulevalidate, required: true, trigger: "blur" },
    ],
  };

  /** 退出弹窗状态 */
  saveFlag = false;

  /** 优惠券信息 */
  couponContent = {};

  /**
   * 选择时间类型
   */
  chooseTimeType() {
    // 共用一个字段 避免时间格式问题 先清空操作
    this.ruleForm.useDateValue = {
      startTime: "" as any,
      endTime: "" as any,
      effectiveDays: "",
    };
  }

  mounted() {
    if (this.$route.params.id) {
      this.getCouponDetail();
    }
  }

  /**
   * 优惠券详情
   */
  getCouponDetail() {
    couponDetail(this.$route.params.id, {}).then((res) => {
      const result = res.data.couponVo;
      const productVos = res.data.discountProductVos;
      this.disType = result.status === 1 ? true : false;
      this.timeRadio = result.startTime ? "setTime" : "immediate";
      this.ruleForm.useDateValue.effectiveDays = result.effectiveDays;
      this.nameId = result.name;
      if (result.startTime) {
        this.ruleForm.useDateValue.startTime = new Date(result.startTime);
        this.ruleForm.useDateValue.endTime = new Date(result.endTime);
      }
      this.couponContent = { ...result, productVos };
    });
  }

  /**
   * 保存发布优惠券
   */
  async save() {
    // await this.formValid();
    this.apointComp.pointGoodsList.forEach((item) => {
      item.productId = item.id;
    });

    const check = this.checkSecond();
    if (!check) {
      return;
    }

    const param = this.dealParam();
    if (Number(param.integral) === 0) {
      this.$message.error("积分值不能小于0");
      return;
    }
    if (this.$route.params.id) {
      this.edit(param);
      return;
    }
    addCoupon(param).then(() => {
      this.saveFlag = true;
      this.$message.success("发布成功");
      this.$router.push({
        name: "integralMallIndex",
        params: { comName: "CouponList" },
      });
    }).catch((err)=>{
       this.$message.error(err);
    })
  }

  /**
   * 处理请求参数
   */
  dealParam() {
    return {
      name: this.nameId,
      effectiveDays:
        this.timeRadio === "immediate"
          ? this.ruleForm.useDateValue.effectiveDays
          : "",
      startTime:
        this.timeRadio === "immediate"
          ? ""
          : new DateUtil("").getYMDs(this.ruleForm.useDateValue.startTime) +
            " 00:00:00",
      endTime:
        this.timeRadio === "immediate"
          ? ""
          : new DateUtil("").getYMDs(this.ruleForm.useDateValue.endTime) +
            " 23:59:59",
      effectiveType: this.timeRadio === "setTime" ? 0 : 1,
      giveType: 2,
      productType: this.apointComp.goodRadio,
      couponProducts: this.apointComp.pointGoodsList,
      id: this.$route.params.id ? (this.couponContent as any).id : "",
      ...this.addComp.couponList[0],
    };
  }

  /**
   * 二次验证条件
   */
  checkSecond() {
    if (this.timeRadio === "setTime") {
      if (
        !this.ruleForm.useDateValue.startTime ||
        !this.ruleForm.useDateValue.endTime
      ) {
        this.$message.error("请输入有效时间");
        return false;
      }
      const start = this.ruleForm.useDateValue.startTime.getTime();
      const end = this.ruleForm.useDateValue.endTime.getTime();
      const now = new Date(new DateUtil("").getYMD(new Date())).getTime();
      if (start > end || start < now) {
        return false;
      }
    } else {
      if (!Number(this.ruleForm.useDateValue.effectiveDays)) {
        this.$message.error("请输入大于0的有效时间");
        return false;
      }
    }

    if (!this.addComp.validType) {
      this.$message.error("请输入活动规则");
      return false;
    }
    if (
      this.apointComp.goodRadio !== 0 &&
      this.apointComp.pointGoodsList.length === 0
    ) {
      this.$message.error("请选择指定商品");
      return false;
    }
    return true;
  }

  /**
   * 验证表单
   */
  formValid() {
    return this.fromRef.validate();
  }

  /**
   * 编辑优惠券
   */
  edit(param) {
    editCoupon(param).then((res) => {
      if (res.code === 200) {
        this.saveFlag = true;
        this.$message.success("编辑成功");
        this.$router.push({
          name: "integralMallIndex",
          params: { comName: "CouponList" },
        });
      }
    });
  }

  beforeRouteLeave(to, from, next) {
    if (this.saveFlag) {
      next();
      return;
    }
    this.$confirm(
      `确定要退出${
        this.$route.params.id ? "编辑" : "发布"
      }积分优惠券页面?退出后，未保存的信息将不会保留!`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      },
    ).then(() => {
      next();
    });
  }
}
</script>

<style lang="scss" scoped>
.title {
  margin: 10px 0px;
  font-weight: bold;
  font-size: 14px;
  margin-bottom: 40px;
}

.remark {
  margin-left: 40px;
  color: #9b9b9b;
}

.pageButtom {
  margin-top: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
